package jp.co.baka.gae.example.controller.view.bbs;

import java.util.ConcurrentModificationException;
import java.util.Date;

import jp.co.baka.gae.example.model.BbsMessage;
import jp.co.baka.gae.example.service.BbsService;
import jp.co.baka.gae.example.util.PerformanceChecker;
import jp.co.baka.gae.lib.MyController;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;

public class InsertBatchController extends MyController {


    private static Log logger = LogFactory.getLog(InsertBatchController.class);

    @Override
    public Navigation run() {


        logger.warn("テストロガー");

        int insNum = super.asInteger("insertBatchNum");

        PerformanceChecker timer = PerformanceChecker.get();
        for(int i=0;i<insNum;i++){

            Long id = BbsService.getNextId();

            DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

            Key key = KeyFactory.createKey(BbsMessage.class.getSimpleName(), id);
            Transaction tx = Datastore.beginTransaction();

            try {
                ds.get(tx, key);

            } catch (EntityNotFoundException e) {


                BbsMessage bbs = new BbsMessage();
                bbs.setId(id);
                bbs.setKey(key);
                bbs.setInsertDate(new Date());
                bbs.setUserName("名前" + i);
                bbs.setContent("内容" + i);

                try {
                    Datastore.put(tx, bbs);
                    tx.commit();
                }catch (ConcurrentModificationException e2) {
                    requestScope("gmnMessage","排他エラーが発生しました");
                    if (tx.isActive()) {
                        tx.rollback();
                        break;
                    }

                }catch (Exception e2) {
                    e.printStackTrace();
                    requestScope("gmnMessage","システムエラー:" + e2.getMessage());
                    break;

                }


            }

        }

        requestScope("processTime",timer.getProcessTimeMills());


        return redirect(basePath);
    }


}